import { Router } from "vue-router";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import { useAsyncRouteStore } from "@/store/modules/asyncRoute";
import { storage } from "@/utils/lib/Storage";

const whiteRouter = ["/login", "/register", "/"];
export function createRouterGuards(router: Router) {
	router.beforeEach((to, from, next) => {
		const token = storage.get(ACCESS_TOKEN);
		if (token) {
			next();
		} else {
			if (whiteRouter.includes(to.path)) {
				next();
			} else {
				next("/login");
			}
		}
	});

	router.afterEach((to, from, next) => {
		// 设置标题
		document.title = (to?.meta?.title as string) || document.title;

		// 设置需要被缓存的组件名
		const asyncRouteStore = useAsyncRouteStore();
		const keepAliveComponents: string[] = asyncRouteStore.keepAliveComponents;
		const currentComponentName: any = to.matched.find(
			(item) => item.name == to.name
		)?.name;
		if (
			currentComponentName &&
			!keepAliveComponents.includes(currentComponentName) &&
			to.meta.isKeepAlive
		) {
			asyncRouteStore.setKeepAliveComponents(currentComponentName);
		}
		console.log(keepAliveComponents);

		const Loading = window["$loading"] || null;
		Loading && Loading.finish();
		// window.scrollTo(0,0);
	});
}
